﻿using System;
using Microsoft.SharePoint.PowerShell;
using Microsoft.SharePoint.Administration;

namespace CodeCounsel.SharePoint2010.DigiD.Cmdlets
{
    public class DigiDSettingsPipeBind : SPCmdletPipeBind<DigiDSettings>
    {
        string _name;
        Guid? _id;

        public DigiDSettingsPipeBind(DigiDSettings settings) : base(settings)
        {
        }

        public DigiDSettingsPipeBind(Guid inputGuid)
        {
            _id = inputGuid;
        }

        public DigiDSettingsPipeBind(string inputString)
        {
            if (inputString != null)
            {
                _name = inputString.Trim();
            }
        }

        protected override void Discover(DigiDSettings instance)
        {
            _name = instance.Name;            
        }

        public override DigiDSettings Read()
        {
            DigiDSettings settings = null;
            if (String.IsNullOrEmpty(_name) == false)
            {
                settings = DigiDService.Local.DigiDSettings[_name];
            }
            else if (_id != null)
            {
                settings = SPFarm.Local.GetObject(_id.Value) as DigiDSettings;
            }
            if (settings == null)
            {
                throw new SPCmdletPipeBindException(String.Format("DigiD config not found for: {0}", _name));
            }
            return settings;
        }
    }
}
